const { ipcMain } = require('electron');
const ftp = require('basic-ftp');
const fs = require('fs');
const path = require('path');
const log = require('electron-log');

// FTP客户端实例
let ftpClient = null;

/**
 * 初始化FTP IPC处理器
 */
function initializeFTPHandlers() {
  // 连接FTP服务器
  ipcMain.handle('ftp-connect', async (event, { host, port, user, password }) => {
    try {
      if (ftpClient) {
        ftpClient.close();
      }

      ftpClient = new ftp.Client();
      ftpClient.ftp.verbose = false; // 关闭详细日志

      await ftpClient.access({
        host,
        port,
        user,
        password,
        secure: false
      });

      log.info(`FTP已连接: ${host}:${port}`);
      return { success: true };
    } catch (error) {
      log.error('FTP连接失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 断开FTP连接
  ipcMain.handle('ftp-disconnect', async () => {
    try {
      if (ftpClient) {
        ftpClient.close();
        ftpClient = null;
        log.info('FTP已断开连接');
      }
      return { success: true };
    } catch (error) {
      log.error('FTP断开连接失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 上传文件
  ipcMain.handle('ftp-upload', async (event, { localPath, remotePath }) => {
    try {
      if (!ftpClient) {
        throw new Error('FTP未连接');
      }

      // 确保远程目录存在
      const remoteDir = path.dirname(remotePath).replace(/\\/g, '/');
      if (remoteDir !== '/' && remoteDir !== '.') {
        await ensureRemoteDir(ftpClient, remoteDir);
      }

      // 上传文件
      await ftpClient.uploadFrom(localPath, remotePath);
      
      log.info(`FTP上传成功: ${localPath} -> ${remotePath}`);
      return { success: true };
    } catch (error) {
      log.error('FTP上传失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 下载文件
  ipcMain.handle('ftp-download', async (event, { remotePath, localPath }) => {
    try {
      if (!ftpClient) {
        throw new Error('FTP未连接');
      }

      // 确保本地目录存在
      const localDir = path.dirname(localPath);
      if (!fs.existsSync(localDir)) {
        fs.mkdirSync(localDir, { recursive: true });
      }

      // 下载文件
      await ftpClient.downloadTo(localPath, remotePath);
      
      log.info(`FTP下载成功: ${remotePath} -> ${localPath}`);
      return { success: true };
    } catch (error) {
      log.error('FTP下载失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 创建远程目录
  ipcMain.handle('ftp-mkdir', async (event, { remotePath }) => {
    try {
      if (!ftpClient) {
        throw new Error('FTP未连接');
      }

      await ensureRemoteDir(ftpClient, remotePath);
      
      log.info(`FTP创建目录成功: ${remotePath}`);
      return { success: true };
    } catch (error) {
      log.error('FTP创建目录失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 列出远程目录
  ipcMain.handle('ftp-list', async (event, { remotePath }) => {
    try {
      if (!ftpClient) {
        throw new Error('FTP未连接');
      }

      const list = await ftpClient.list(remotePath);
      return { success: true, files: list };
    } catch (error) {
      log.error('FTP列出目录失败:', error);
      return { success: false, error: error.message };
    }
  });

  log.info('FTP IPC处理器已初始化');
}

/**
 * 递归创建远程目录
 */
async function ensureRemoteDir(client, dirPath) {
  const parts = dirPath.split('/').filter(p => p);
  let currentPath = '';

  for (const part of parts) {
    currentPath += '/' + part;
    try {
      await client.ensureDir(currentPath);
    } catch (error) {
      // 目录可能已存在，忽略错误
      log.debug(`目录可能已存在: ${currentPath}`);
    }
  }
}

/**
 * 清理FTP连接
 */
function cleanupFTP() {
  if (ftpClient) {
    try {
      ftpClient.close();
      log.info('FTP连接已清理');
    } catch (error) {
      log.error('清理FTP连接失败:', error);
    }
  }
}

module.exports = {
  initializeFTPHandlers,
  cleanupFTP
};
